package com.demo.annotation;

import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Supplier;

@RestController
@RequestMapping("/async")
public class AsyncAnno {

    @Async
    @RequestMapping("/test")
    public void test() throws InterruptedException {
        Thread.sleep(5000);
        System.out.println(1);
    }

//    @Async
    @RequestMapping("/test1")
    public String test1() {

        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            try {
                return ddd();
            } catch (InterruptedException e) {
                e.printStackTrace();
                return "掛了";
            }
        });

        try {
            return future.get(3, TimeUnit.SECONDS);
        }catch (Exception e){
            return "超時了";
        }
    }

    //模拟接口耗时
    public String ddd() throws InterruptedException {
        Thread.sleep(5_000);
        System.out.println("wpz");
        return "wpz";
    }

}
